<?php

namespace App\Admin\Forms;

use App\Jobs\GenerateAgreementJob;
use App\Jobs\JobQueue;
use App\Models\Category;
use App\Models\ProjectAgreement;
use App\Models\User;
use App\Support\Data;
use Dcat\Admin\Admin;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Widgets\Form;

class GenAgreementForm extends Form
{
    use LazyWidget;
    // 处理请求
    public function handle(array $input)
    {

        $projectRepository = new \App\Admin\Repositories\Project();
        $projectID = $this->payload['project_id'] ?? 0;
        $projectModel = $projectRepository->model()->where('id', $projectID)->first();

        $feeTypeArr = json_decode($projectModel->fee_type, true);
        $fee_type_key = 0;
        $fee_type_key = $feeTypeArr[$input['fee_type_key']];
        if ($input['before_after_tax'] == 2) {
            list($tax, $fee_type_key) = Data::getTaxRate($feeTypeArr[$input['fee_type_key']]);
        }

        $activeDateInfo = explode(' ', $input['active_date']);

        $model = new ProjectAgreement();

        $userModel = User::find($this->payload['uid']);
        $expenseType = $projectRepository::getFeeTypeOptions();

        $user = [
            'id_number' => $userModel['id_number'],
            'phone' => $userModel['phone'],
            'unit' => $userModel['unit'],
            'fee_type_name' => $expenseType[$input['fee_type_key']],
        ];
        // 项目编码
        $agreement_code = 'TT' . date('Ymd') . random_int(100000, 999999);
        $model->agreement_code = $agreement_code;

        $model->project_id = $projectID;
        $model->user_id = $this->payload['uid'] ?? 0;
        $model->user_auth_name = $input['user_auth_name'];
        $model->bank_card = $input['bank_card'] ?? '';
        $model->bank_name = $input['bank_name'] ?? '';
        $model->bank_addr = $input['bank_addr'] ?? '';
        $model->before_after_tax = $input['before_after_tax'];
        $model->role = $input['role'] ?? '';
        $model->fee_type_key = $input['fee_type_key'] ?? '';
        $model->fee_type_value = $fee_type_key ?? '';
        $model->active_date = $activeDateInfo[0] ?? null;
        $model->active_week = $activeDateInfo[1] ? ('星期' . $activeDateInfo[1]) : '';
        $model->active_time_begin = $input['active_time_begin'] ?? null;
        $model->active_time_end = $input['active_time_end'] ?? null;
        $result = $model->save();

        if ($result) {
            GenerateAgreementJob::dispatch($projectModel, $model, $user)->onQueue(JobQueue::GENERATE_AGREEMENT);
            // ->onQueue(JobQueue::GENERATE_AGREEMENT)
            return $this->response()->success('成功')->refresh();
        } else {
            return $this->response()->error('失败');
        }
    }

    public function form()
    {

        $projectRepository = new \App\Admin\Repositories\Project();
        $projectID = $this->payload['project_id'] ?? 0;
        $uid = $this->payload['uid'] ?? 0;
        $userModel = User::find($uid);
        $projectModel = $projectRepository->model()->where('id', $projectID)->first();
        if (empty($userModel->bank_number) || empty($userModel->bank_opening) || empty($userModel->bank_account_open_local)) {
            return $this->response()->error('请先完善银行卡信息');
        }
        $this->text('user_auth_name')->value($userModel->realname)->readOnly()->required();
        $this->text('bank_card')->value($userModel->bank_number)->readOnly()->required();
        $this->text('bank_name')->value($userModel->bank_opening)->readOnly()->required();
        $this->text('bank_addr')->value($userModel->bank_account_open_local)->readOnly()->required();
        $this->select('role')->options($projectRepository::getFeeTypeOptions());
        $this->radio('before_after_tax', '税前/税后金额')->options($projectRepository::getBefoeAfterTax())->default(1);
        $this->select('fee_type_key')
            ->options(function () use ($projectRepository, $projectModel) {
                if (empty($projectModel->fee_type)) {
                    return [];
                }
                $return = [];
                $feeTypeMap = json_decode($projectModel->fee_type, true);
                foreach ($projectRepository::getFeeTypeOptions() as $k => $v) {
                    if ($feeTypeMap[$k] ?? '') {
                        $return[$k] = '类型:' . $v . ' - 金额:' . $feeTypeMap[$k];
                    }
                }
                return $return;
            })
            ->required();
        $this->datetime('active_date')->format('YYYY-MM-DD dd')->required();
        $this->time('active_time_begin')->format('HH:mm');
        $this->time('active_time_end')->format('HH:mm');
    }

    // 返回表单数据，如不需要可以删除此方法
    public function
    default()
    {
        $projectID = $this->payload['project_id'] ?? 0;
        $uid = $this->payload['uid'] ?? 0;
        $lastItem = ProjectAgreement::where(['project_id' => $projectID, 'user_id' => $uid])
            ->orderBy('id', 'desc')
            ->first();
        if (empty($lastItem)) {
            return [];
        }
        return [
            'user_auth_name' => $lastItem['user_auth_name'] ?? '',
            'bank_card' => $lastItem['bank_card'],
            'bank_name' => $lastItem['bank_name'],
            'bank_addr' => $lastItem['bank_addr'],
            'role' => $lastItem['role'],
            'fee_type_key' => $lastItem['fee_type_key'],
            'active_date' => $lastItem['active_date'],
            'active_time_begin' => $lastItem['active_time_begin'],
            'active_time_end' => $lastItem['active_time_end'],
        ];
    }
}
